package com.breakfast.fun.ui.mall.cart;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.adapter.mall.CartGoodAdapter;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.dao.Address;
import com.breakfast.fun.dao.AddressDao;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.GoodCart;
import com.breakfast.fun.dao.GoodCartDao;
import com.breakfast.fun.data.entity.mall.SubmitGoodsItem;
import com.breakfast.fun.data.entity.mall.SubmitGoodsOrder;
import com.breakfast.fun.data.entity.user.recharge.PayBean;
import com.breakfast.fun.event.GoodEvent;
import com.breakfast.fun.event.MallAddressEvent;
import com.breakfast.fun.ui.mall.address.MallAddressActivity;
import com.breakfast.fun.ui.user.pay.BFPayActivity;
import com.breakfast.fun.util.JumpUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.CustomDialog;
import com.breakfast.fun.view.widget.TitleBarView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class GoodCartActivity extends BaseActivity<GoodCartPresenter, GoodCartModel> implements GoodCartContract.View {

    @Bind(R.id.tbv_good_cart)
    TitleBarView mTbvGoodCart;
    @Bind(R.id.lv_cart_good)
    ListView mLvCartGood;
    @Bind(R.id.ll_cart_good)
    LinearLayout mLlCartGood;
    @Bind(R.id.iv_cart_empty)
    ImageView mIvCartEmpty;
    @Bind(R.id.tv_cart_count)
    TextView mTvCartCount;
    @Bind(R.id.rl_cart_count)
    RelativeLayout mRlCartCount;
    @Bind(R.id.tv_cart_bottom_total)
    TextView mTvCartBottomTotal;
    @Bind(R.id.tv_cart_price)
    TextView mTvCartPrice;
    @Bind(R.id.btn_cart_submit)
    Button mBtnCartSubmit;
    @Bind(R.id.rl_cart_bottom)
    RelativeLayout mRlCartBottom;

    private GoodCartDao mGoodCartDao;
    private AddressDao mAddressDao;
    private CustomDialog mDialog;
    private View mHeaderView;
    private ViewHolder holder;

    private CartGoodAdapter adapter;

    //从商城物品跳转进来先不显示优惠券
    private Boolean isFromMall;

    @Override
    public int getLayoutId() {
        return R.layout.activity_good_cart;
    }

    @Override
    public void initView() {

        EventBus.getDefault().register(this);
        mGoodCartDao = DaoMaster.newDevSession(context, "zaofan.db").getGoodCartDao();
        mAddressDao = DaoMaster.newDevSession(context, "zaofan.db").getAddressDao();

        isFromMall = getIntent().getBooleanExtra("isFromMall", false);

        mTbvGoodCart.setAll("购物车");
        mTbvGoodCart.setRightImg(R.drawable.ic_recover);
        mTbvGoodCart.setBack(this);
        mTbvGoodCart.setRightListener(v -> {
            recoverProduct();
        });

        mHeaderView = LayoutInflater.from(this).inflate(R.layout.layout_user_cart_head, null);
        holder = new ViewHolder(mHeaderView);
        holder.mLlCartTime.setVisibility(View.GONE);

        mLvCartGood.addHeaderView(mHeaderView);

        holder.mRlCartAddress.setOnClickListener(v -> {
            if (Constant.getUserData() == null) {
                T.show("请登录");
                JumpUtil.toLogin(context);
                return;
            }
            Intent intent = new Intent(GoodCartActivity.this, MallAddressActivity.class);
            startActivity(intent);
        });

        holder.mRlCartNoAddress.setOnClickListener(v -> {
            if (Constant.getUserData() == null) {
                T.show("请登录");
                JumpUtil.toLogin(context);
                return;
            }
            Intent intent = new Intent(GoodCartActivity.this, MallAddressActivity.class);
            startActivity(intent);
        });

        Address address = mAddressDao.loadByRowId(2);
        if (address != null) {
            holder.mTvCartMobile.setText(address.getMobile());
            holder.mTvCartName.setText(address.getName());
            holder.mTvCartAddress.setText(address.getAddress());
            holder.mRlCartAddress.setVisibility(View.VISIBLE);
            holder.mRlCartNoAddress.setVisibility(View.GONE);
        } else {
            holder.mRlCartNoAddress.setVisibility(View.VISIBLE);
            holder.mRlCartAddress.setVisibility(View.GONE);
        }

        if (isFromMall) {
            holder.mRlCartCoupon.setVisibility(View.GONE);
        }

        mBtnCartSubmit.setOnClickListener(v -> {
            if (holder.mRlCartAddress.getVisibility() != View.VISIBLE) {
                T.show("请先添加地址");
                return;
            }
            if (adapter.getCount() == 0) {
                T.show("购物车为空,请添加商品");
                return;
            }

            submitOrder();
        });

        adapter = new CartGoodAdapter(context, mGoodCartDao.loadAll());
        mLvCartGood.setAdapter(adapter);
    }

    private void submitOrder() {
        if (Constant.getUserData() == null) {
            T.show("请登录");
            JumpUtil.toLogin(context);
            return;
        }
        SubmitGoodsOrder submitOrder = new SubmitGoodsOrder();
        submitOrder.setAddress(mAddressDao.loadByRowId(2).getAddressId());
        submitOrder.setSignName(holder.mTvCartName.getText().toString());
        submitOrder.setAddressName(holder.mTvCartAddress.getText().toString());
        submitOrder.setMobile(holder.mTvCartMobile.getText().toString());
        submitOrder.setMark(holder.mEtCartMark.getText().toString());
        submitOrder.setUserId(Constant.getUserData().getId());

        List<SubmitGoodsItem> shopData = new ArrayList<>();
        SubmitGoodsItem item;

        mGoodCartDao = DaoMaster.newDevSession(context, "zaofan.db").getGoodCartDao();

        double totalPrice = 0;

        List<GoodCart> goodCarts = mGoodCartDao.loadAll();
        for (int i = 0; i < goodCarts.size(); i++) {
            item = new SubmitGoodsItem();
            GoodCart goodCart = goodCarts.get(i);
            item.setGoodAccount(goodCart.getCount());
            item.setGoodId(goodCart.getGoodId());
            item.setGoodImage(goodCart.getImage());
            item.setGoodName(goodCart.getName());
            item.setBigImage(goodCart.getBigImage());
            shopData.add(item);
            totalPrice += goodCart.getTotalPrice();
        }

        submitOrder.setTotalPrice(totalPrice);

        submitOrder.setShopData(shopData);

        String order = new Gson().toJson(submitOrder);
        presenter.submitOrder(order);
    }

    @Override
    public void showOrderInfo(PayBean data) {
        T.show("订单提交成功");
        mGoodCartDao.deleteAll();
        Intent intent = new Intent(this, BFPayActivity.class);
        intent.putExtra("payBean", data);
        intent.putExtra("isFromMall", true);
        startActivity(intent);
        this.finish();
    }


    private void recoverProduct() {
        mDialog = new CustomDialog(GoodCartActivity.this, R.style.dialog_style,
                R.layout.dialog_custom, "提示", "确定要清空购物车吗？", false, false, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
                mGoodCartDao.deleteAll();
                mGoodCartDao = DaoMaster.newDevSession(context, "zaofan.db").getGoodCartDao();
                adapter = new CartGoodAdapter(context, mGoodCartDao.loadAll());
                mLvCartGood.setAdapter(adapter);
            }
        });
        mDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GoodEvent event) {
        if (event.getTotalNum() > 0) {
            mTvCartCount.setVisibility(View.VISIBLE);
        } else {
            mTvCartCount.setVisibility(View.GONE);
        }
        mTvCartCount.setText(event.getTotalNum() + "");
        if (event.getTotalPrice() < 0) {
            event.setTotalPrice(0);
        }
        mTvCartPrice.setText(String.format("%.2f", event.getTotalPrice()));

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventAddress(MallAddressEvent event) {
        Address address = new Address();
        address.setId((long) 2);
        address.setMobile(event.getMobile());
        address.setAddress(event.getDetail());
        address.setName(event.getName());
        mAddressDao.insertOrReplace(address);

        holder.mRlCartNoAddress.setVisibility(View.GONE);
        holder.mRlCartAddress.setVisibility(View.VISIBLE);
        holder.mTvCartMobile.setText(address.getMobile());
        holder.mTvCartName.setText(address.getName());
        holder.mTvCartAddress.setText(address.getAddress());
    }

    @Override
    protected void destroyView() {
        super.destroyView();
        EventBus.getDefault().unregister(this);
    }

    static class ViewHolder {
        @Bind(R.id.tv_cart_name)
        TextView mTvCartName;
        @Bind(R.id.tv_cart_mobile)
        TextView mTvCartMobile;
        @Bind(R.id.tv_cart_address)
        TextView mTvCartAddress;
        @Bind(R.id.ll_cart_head_address)
        LinearLayout mLlCartHeadAddress;
        @Bind(R.id.rl_cart_address)
        RelativeLayout mRlCartAddress;
        @Bind(R.id.rl_cart_no_address)
        RelativeLayout mRlCartNoAddress;
        @Bind(R.id.rl_cart_coupon)
        RelativeLayout mRlCartCoupon;
        @Bind(R.id.tv_cart_send_time_left)
        TextView mTvCartSendTimeLeft;
        @Bind(R.id.tv_cart_send_time)
        TextView mTvCartSendTime;
        @Bind(R.id.rl_cart_send_time)
        RelativeLayout mRlCartSendTime;
        @Bind(R.id.et_cart_mark)
        EditText mEtCartMark;
        @Bind(R.id.ll_cart_head)
        LinearLayout mLlCartHead;
        @Bind(R.id.ll_cart_time)
        LinearLayout mLlCartTime;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
